package com.pkufinalproject.cleverreminder.controller;

import com.pkufinalproject.cleverreminder.hibernate.entity.User;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    private final static SessionFactory sf = new Configuration().configure().buildSessionFactory();

    /**
     * 根据用户名检索用户对象
     * @param name 用户名
     * @return User对象
     */
    public static User retrieveUser(String name) {
        User user = null;
        Session session = sf.openSession();
        Criteria criteria = session.createCriteria(User.class).add(
                Restrictions.like("username",name));
        List<User> userList = criteria.list();
        if (!userList.isEmpty()) user = userList.get(0);
        session.close();
        return user;
    }

    @RequestMapping("retrieve")
    public static String strRetrieveUser(String name) {
        User user = retrieveUser(name);
        if (user == null) return "no user found";
        return user.toString();
    }


    /**
     * 注册新用户，但不能和已有的用户的name重复
     * @param name 要注册的用户名
     * @param password 要注册的用户密码
     * @return 返回注册是否成功的文字提示
     */
    @RequestMapping("register")
    public static String registerUser(String name, String password) {
        if (retrieveUser(name) != null) return "user already exists";
        Session session = sf.openSession();
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        session.save(user);
        session.beginTransaction().commit();
        session.close();
        return "user registered successfully";
    }
}